問題一、字串replace 用法?
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?'; //這是一個字串格式
console.log(p.replace('dog', 'monkey'));
// Expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?" 只有第一次出現的字串被取代
const regex = /Dog/i;
console.log(p.replace(regex, 'ferret'));
// Expected output: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?" 只有第一次出現的字串被取代
第三個例子中,const regex = /Dog/i;
:這是一個正規表達式 regex
,它是不區分大小寫(i
標誌)的,並且尋找 "Dog" 這個文字。將第一個dog替換成ferret後,再回傳原來的字串。
問題二、replace (pattern, replacement) 是什麼?
(一)pattern :
(二)replacement :
$$ : 插入字符 "$" 本身。
$& : 插入
$`
$'
$n
$<Name>
是函式的話,則將為每個匹配的地方調用它,並回傳值。
pattern 如果是" ",會在字串前面加上空格
"xxx".replace("", "_"); // "_xxx"
這個程式碼需要參考上面的Specifying a string as the replacement:
"foo".replace(/(f)/, "$2");
// "$2oo"; the regex doesn't have the second group
在這個正規表達式中,只有一個 Capturing group,所以直接替換
"foo".replace("f", "$1");
// "$1oo"; the pattern is a string, so it doesn't have any groups
因為pattern只是一個字串,而非正規表達式,故沒有Capturing group
"foo".replace(/(f)|(g)/, "$2");
// "oo"; the second group exists but isn't matched
有兩個Capturing group
Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace